package paskal.ui.components;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.plaf.SliderUI;
import javax.swing.plaf.basic.BasicSliderUI;

/*Slider which shows download progress from url*/
public class ProgressSlider extends Slider {
	private static final long serialVersionUID = -589656226132467760L;

	private double loadedPercentage = 1.0;
	private Color loadedColor = new Color(0x0b2e3a);

	public ProgressSlider() {
		super();
	}

	@Override
	protected SliderUI getOwnUI() {
		if ((trackColorAfter != null) && (trackColorBefore != null)) {
			loadedColor = new Color(
					(trackColorBefore.getRed() + trackColorAfter.getRed()) / 2,
					(trackColorBefore.getGreen() + trackColorAfter.getGreen()) / 2,
					(trackColorBefore.getBlue() + trackColorAfter.getBlue()) / 2);
		}
		return new BasicSliderUI(this) {
			@Override
			public void paintTrack(Graphics g) {
				if ((trackBefore != null) && (trackAfter != null)) {
					g.setColor(new Color(0x000));
					g.drawImage(trackAfter, trackRect.x, trackRect.y
							+ (trackRect.height - trackSize) / 2,
							thumbRect.x, trackSize, null);
					g.setColor(loadedColor);
					g.fillRect(trackRect.x, trackRect.y
							+ (trackRect.height - trackSize) / 2 + 2,
							(int) (trackRect.width * loadedPercentage),
							trackSize - 2);
					g.drawImage(trackBefore, trackRect.x, trackRect.y
							+ (trackRect.height - trackSize) / 2,
							thumbRect.x, trackSize, null);
				} else if ((trackColorAfter != null)
						&& (trackColorBefore != null)) {
					g.setColor(trackColorAfter);
					g.fillRect(trackRect.x, trackRect.y
							+ (trackRect.height - trackSize) / 2,
							trackRect.width, trackSize);
					g.setColor(loadedColor);
					g.fillRect(trackRect.x, trackRect.y
							+ (trackRect.height - trackSize) / 2,
							(int) (trackRect.width * loadedPercentage),
							trackSize);
					g.setColor(trackColorBefore);
					g.fillRect(trackRect.x, trackRect.y
							+ (trackRect.height - trackSize) / 2,
							thumbRect.x, trackSize);
				} else {
					super.paintTrack(g);
				}
			}

			@Override
			public void paintThumb(Graphics g2) {
				if (thumb != null) {
					Graphics2D g = (Graphics2D) g2;
					g.drawImage(thumb.getCurrentIcon(), thumbRect.x,
							thumbRect.y
									+ (thumbRect.height - thumb
											.getCurrentIcon().getHeight()) / 2,
							null);
				} else {
					super.paintThumb(g2);
				}

			}

			@Override
			public void paintFocus(Graphics g) {
			}

			@Override
			public void paintLabels(Graphics g) {
			}

			@Override
			public void paintTicks(Graphics g) {
			}
		};
	}

	public void setLoadedPercentage(double loadedPercentage) {
		this.loadedPercentage = loadedPercentage;
		repaint();
	}
}
